package cn.iocoder.yudao.module.system.controller.admin.chaoshun;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.enums.CommonSfEnum;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.controller.admin.chaoshun.vo.sp.*;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserUpdateStatusReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.chaoshun.ChaoshunSpDO;
import cn.iocoder.yudao.module.system.service.chaoshun.ChaoshunSpService;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.system.enums.DictTypeConstants.*;

@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/chaoshun/info")
@Validated
public class ChaoshunController {

    @Resource
    private ChaoshunSpService chaoshunSpService;
    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;

    @PostMapping("/create")
    @Operation(summary = "新增商品信息")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:create')")
    public CommonResult<String> createSp(@Valid @RequestBody ChaoshunSpSaveReqVO reqVO) {
        String ydh = chaoshunSpService.createChaoshunSp(reqVO);
        return success(ydh);
    }

    @PutMapping("update")
    @Operation(summary = "修改商品信息")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:update')")
    public CommonResult<Boolean> updateSp(@Valid @RequestBody ChaoshunSpSaveReqVO reqVO) {
        chaoshunSpService.updateChaoshunSp(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "物流信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:delete')")
    public CommonResult<Boolean> deleteSp(@RequestParam("id") Long id) {
        chaoshunSpService.deleteSp(id);
        return success(true);
    }

    @PutMapping("/return")
    @Operation(summary = "物流信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:return')")
    public CommonResult<Boolean> returnSp(@RequestParam("id") Long id) {
        chaoshunSpService.returnSp(id);
        return success(true);
    }

    @PutMapping("/delay")
    @Operation(summary = "物流信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:delay')")
    public CommonResult<Boolean> delaySp(@RequestParam("id") Long id) {
        chaoshunSpService.delaySp(id);
        return success(true);
    }

//    @PutMapping("/update-password")
//    @Operation(summary = "重置用户密码")
//    @PreAuthorize("@ss.hasPermission('chaoshun:info:update-password')")
//    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody UserUpdatePasswordReqVO reqVO) {
//        userService.updateUserPassword(reqVO.getId(), reqVO.getPassword());
//        return success(true);
//    }

    @PutMapping("/update-status")
    @Operation(summary = "修改用户状态")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        chaoshunSpService.updateChaoshunSpStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @PutMapping("/update-sfsm")
    @Operation(summary = "修改上否上门状态")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody ChaoshunSpUpdateSfsmReqVO reqVO) {
        chaoshunSpService.updateChaoshunSpSfsm(reqVO.getId(), reqVO.getSfsm());
        return success(true);
    }

    @PostMapping("/fsdx")
    @Operation(summary = "发送短信")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:update')")
    public CommonResult<Boolean> fsdx(@Valid @RequestBody ChaoshunSpFsdxReqVO reqVO) {
        chaoshunSpService.fsdx(reqVO.getIdList());
        return success(true);
    }

    @PostMapping("/getYhxxByXm")
    @Operation(summary = "根据用户姓名获取用户信息")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:list')")
    public CommonResult<List<YhxxRespVO>> getYhxxByXm(@Valid @RequestBody YhxmVO yhxmVO) {
        // 获得商品信息分页列表
        List<ChaoshunSpDO> yhxxList = chaoshunSpService.getYhxxByXm(yhxmVO);
        List<YhxxRespVO> resultList = new ArrayList<>();
        boolean sfFhr = StrUtil.isNotEmpty(yhxmVO.getFhr());
        for (ChaoshunSpDO spDO : yhxxList) {
            YhxxRespVO yhxxRespVO = new YhxxRespVO();
            String value;
            if (sfFhr) {
                value = spDO.getFhr() + StrPool.DASHED + spDO.getFhdh();
            } else {
                value = spDO.getShr2() + StrPool.DASHED + spDO.getShdh() + StrPool.DASHED + spDO.getSpmc();
            }
            yhxxRespVO.setValue(value);
            yhxxRespVO.setLabel(value);
            resultList.add(yhxxRespVO);
        }
        // 拼接数据
        return success(resultList);
    }

    @GetMapping("/page")
    @Operation(summary = "获得商品列表")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:list')")
    public CommonResult<PageResult<ChaoshunspRespVO>> getSpPage(@Valid SpPageReqVO pageReqVO) {
        // 获得商品信息分页列表
        PageResult<ChaoshunSpDO> pageResult = chaoshunSpService.getSpPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // 拼接数据
        return success(new PageResult<>(CollectionUtils.convertList(pageResult.getList(), sp -> {
            ChaoshunspRespVO respVO = BeanUtil.copyProperties(sp, ChaoshunspRespVO.class);
            Integer yccs = respVO.getYccs();
            if (yccs > 0) {
                respVO.setTz(" 延" + yccs);
            }
            if (CommonSfEnum.isEnable(respVO.getSffh())) {
                respVO.setTz(StrUtil.trimToEmpty(respVO.getTz()) + " 返");
            }
            if (CommonSfEnum.isEnable(respVO.getSfbl())) {
                respVO.setTz(StrUtil.trimToEmpty(respVO.getTz()) + " 补");
            }
            respVO.setYffsmc(DictFrameworkUtils.getDictDataLabel(COMMON_YFZFFS, sp.getYffs()));
            respVO.setHkfsmc(DictFrameworkUtils.getDictDataLabel(COMMON_HKZFFS, sp.getHkfs()));
            respVO.setSfsmmc(DictFrameworkUtils.getDictDataLabel(COMMON_SF, sp.getSfsm()));
            return respVO;
        }),
                pageResult.getTotal()));
    }

    @GetMapping("/pageDdy")
    @Operation(summary = "获得待打印的商品列表")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:list')")
    public CommonResult<PageResult<ChaoshunspRespVO>> pageDdy(@Valid SpPageReqVO pageReqVO) {
        // 获得商品信息分页列表
        PageResult<ChaoshunSpDO> pageResult = chaoshunSpService.dySpPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        List<ChaoshunspRespVO> spList = CollectionUtils.convertList(pageResult.getList(), user -> BeanUtil.copyProperties(user, ChaoshunspRespVO.class));
        for (ChaoshunspRespVO sp : spList) {
            sp.setYffsmc(DictFrameworkUtils.getDictDataLabel(COMMON_YFZFFS, sp.getYffs()));
            sp.setHkfsmc(DictFrameworkUtils.getDictDataLabel(COMMON_HKZFFS, sp.getHkfs()));
        }
        // 拼接数据
        return success(new PageResult<>(spList,
                pageResult.getTotal()));
    }

//    @GetMapping({"/list-all-simple", "/simple-list"})
//    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
//    public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
//        List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
//        // 拼接数据
//        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
//                convertList(list, AdminUserDO::getDeptId));
//        return success(UserConvert.INSTANCE.convertSimpleList(list, deptMap));
//    }
//
    @GetMapping("/get")
    @Operation(summary = "获得商品详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:query')")
    public CommonResult<ChaoshunspRespVO> getChaoshunSp(@RequestParam("id") Long id) {
        ChaoshunSpDO chaoshunSp = chaoshunSpService.getChaoshunSp(id);
        ChaoshunspRespVO sp = BeanUtil.copyProperties(chaoshunSp, ChaoshunspRespVO.class);
        sp.setYffsmc(DictFrameworkUtils.getDictDataLabel(COMMON_YFZFFS, sp.getYffs()));
        sp.setHkfsmc(DictFrameworkUtils.getDictDataLabel(COMMON_HKZFFS, sp.getHkfs()));
        sp.setSfsmmc(DictFrameworkUtils.getDictDataLabel(COMMON_SF, sp.getSfsm()));
        return success(sp);
    }

    @GetMapping("/export")
    @Operation(summary = "导出商品")
    @PreAuthorize("@ss.hasPermission('chaoshun:info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSpList(@Validated SpPageReqVO exportReqVO,
                               HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        exportReqVO.setSfdc(0);
        List<ChaoshunSpDO> list = chaoshunSpService.getSpPage(exportReqVO).getList();
        // 输出 Excel
        ExcelUtils.write(response, "朝顺物流.xls", "数据", ChaoshunspRespVO.class,
                CollectionUtils.convertList(list, sp -> BeanUtil.copyProperties(sp, ChaoshunspRespVO.class)));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入物流信息模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<SpImportExcelVO> list = Arrays.asList(
                SpImportExcelVO.builder().spmc("手机").id(1L).shr2("张三").shdh("13145193682").js(5).yf("666").yffs(0).hk("3000")
                        .hkfs(1).fhr("李四").fhdh("16651117024").sfsm(1).shdz("邳州市运河镇新苏广场").remark("加急加快").createTime(LocalDateTime.now())
                        .status(CommonStatusEnum.ENABLE.getStatus()).build()
        );
        // 输出
        ExcelUtils.write(response, "yudao商品导入模板.xls", "商品列表", SpImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入商品")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('chaoshun:info:import')")
    public CommonResult<SpImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                    @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport,
                                                    @RequestParam(value = "sfOld", required = false, defaultValue = "false") Boolean sfOld) throws Exception {
        // 若是本系统导出的excel
        if (file.getOriginalFilename().startsWith("yudao") || !sfOld) {
            List<SpImportExcelVO> list = ExcelUtils.read(file, SpImportExcelVO.class);
            return success(chaoshunSpService.importSpList(list, updateSupport));
        }
        // 若是老系统导出的excel
        List<SpImportExcelOldVO> allSplist = ExcelUtils.read(file, SpImportExcelOldVO.class, 4);
        List<SpImportExcelOldVO> allOldSplist = allSplist.stream().filter(sp -> StrUtil.isNotEmpty(sp.getYdh()) && !"运单号".equals(sp.getYdh()) && !sp.getYdh().startsWith("总合计")).collect(Collectors.toList());

        int year2pre = LocalDate.now().getYear() / 100;
        List<SpImportExcelVO> list = BeanUtil.copyToList(allOldSplist, SpImportExcelVO.class).stream().map(sp->{
            String ydh = sp.getYdh();
            if (StrUtil.isNotEmpty(ydh) && ydh.length() > 6) {
                sp.setCreateTime(LocalDateTime.of(Integer.parseInt(year2pre + ydh.substring(0, 2)), Integer.parseInt(ydh.substring(2, 4)), Integer.parseInt(ydh.substring(4, 6)), 0, 0, 0));
            }
            return sp;
        }).collect(Collectors.toList());
        return success(chaoshunSpService.importSpList(list, updateSupport));

    }

}
